import {
	createStore
} from 'vuex'

const store = createStore({
	state() {
		return {
			records: [],
			currentMonth: (() => {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				return `${year}-${month}`;
			})()
		}
	},

	getters: {
		monthlyStats: (state) => {
			const [year, month] = state.currentMonth.split('-').map(Number)


			const monthlyRecords = state.records.filter(record => {
				const [recordYear, recordMonth] = record.date.split('-').map(Number)
				return recordYear === year && recordMonth === month
			})

			const totalHours = monthlyRecords.reduce((sum, record) => sum + parseFloat(record.hours), 0)

			const totalAmount = monthlyRecords.reduce((sum, record) => {
				const hours = parseFloat(record.hours)
				const rate = parseFloat(record.hourlyRate)
				// 确保计算时处理好0的情况
				return sum + (hours * (rate || 0))
			}, 0)

			// 计算工作天数（不同日期的数量）
			const workdaysSet = new Set(monthlyRecords.map(record => record.date))
			const workdays = workdaysSet.size

			return {
				totalHours: totalHours.toFixed(1),
				totalAmount: totalAmount.toFixed(2),
				workdays
			}
		}
	},

	mutations: {
		SET_RECORDS(state, records) {
			state.records = records
		},

		SET_CURRENT_MONTH(state, month) {
			state.currentMonth = month
		},

		ADD_RECORD(state, record) {
			state.records.push(record)
		},

		UPDATE_RECORD(state, updatedRecord) {
			const index = state.records.findIndex(r => r.id === updatedRecord.id)
			if (index !== -1) {
				state.records.splice(index, 1, updatedRecord)
			}
		},

		DELETE_RECORD(state, recordId) {
			state.records = state.records.filter(r => r.id !== recordId)
		}
	},

	actions: {
		async loadRecords({ commit }) {
			return new Promise((resolve, reject) => {
				try {
					// 使用 try-catch 包裹存储操作
					let records
					try {
						records = uni.getStorageSync('records')
					} catch (storageError) {
						console.error('读取存储失败:', storageError)
						records = []
					}

					// 数据验证和清理
					if (!Array.isArray(records)) {
						console.warn('存储的记录不是数组，重置为空数组')
						records = []
					}

					// 过滤无效记录并添加必要的默认值
					const validRecords = records.filter(record => {
						return record && 
							   typeof record === 'object' &&
							   record.id &&
							   record.date &&
							   record.period &&
							   record.hours
					}).map(record => ({
						...record,
						hourlyRate: parseFloat(record.hourlyRate) || 0,
						hours: parseFloat(record.hours) || 0
					}))

					// 按日期降序排序
					validRecords.sort((a, b) => new Date(b.date) - new Date(a.date))

					// 提交到 store
					commit('SET_RECORDS', validRecords)
					resolve(validRecords)
				} catch (error) {
					console.error('loadRecords 失败:', error)
					// 出错时也要更新状态，避免显示旧数据
					commit('SET_RECORDS', [])
					reject(error)
				}
			})
		},

		async saveRecord({
			commit,
			state
		}, record) {
			try {
				// 检查是否存在重复时段
				const sameDayRecords = state.records.filter(r =>
					r.date === record.date &&
					(!record.id || r.id !== record.id)
				)

				const existingPeriod = sameDayRecords.find(r => r.period === record.period)
				if (existingPeriod) {
					throw new Error(`当前日期${record.date}的该时段已有记录`)
				}

				// 确保时薪是数字
				const recordToSave = {
					...record,
					hourlyRate: parseFloat(record.hourlyRate) || 0
				}

				let records = [...state.records]

				if (record.id) {
					// 更新现有记录
					const index = records.findIndex(r => r.id === record.id)
					if (index !== -1) {
						records[index] = record
						commit('UPDATE_RECORD', record)
					}
				} else {
					// 添加新记录
					const newRecord = {
						...record,
						id: Date.now().toString(),
						createdAt: Date.now(),
						updatedAt: Date.now()
					}
					records.push(newRecord)
					commit('ADD_RECORD', newRecord)
				}

				// 保存到本地存储
				uni.setStorageSync('records', records)

			} catch (e) {
				console.error('保存记录失败:', e)
				throw e
			}
		},

		async deleteRecord({
			commit,
			state
		}, recordId) {
			try {
				const records = state.records.filter(r => r.id !== recordId)
				uni.setStorageSync('records', records)
				commit('DELETE_RECORD', recordId)
			} catch (e) {
				console.error('删除记录失败:', e)
				throw e
			}
		}
	}
})

export default store